﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 07/07/2010
    /// Modified by Vietlv
    /// Modified date : 02/07/2011
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Product)]
    public class DemandsController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /Demands/
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("demand.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("demand.orderDir", "orderDir", "desc").ToString();
                    int catID = Convert.ToInt32(UserState.getUserStateFromRequest("demand.CurrentCat", "CurrentCat", 0));
                    int demandTypeID = Convert.ToInt32(UserState.getUserStateFromRequest("demandType.CurrentType", "DemandTypeID", 0)); // Inserted by Vietlv (AddDate: 25//07/2011)
                    string strPub = UserState.getUserStateFromRequest("demand.CurrentPubStatus", "CurrentPubStatus", "").ToString();
                    string keyword = UserState.getUserStateFromRequest("demand.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("demand.pageSize", "PageSize", 20).ToString());

                    int? currentPub = null;
                    if (!string.IsNullOrEmpty(strPub))
                        currentPub = Convert.ToInt32(strPub);

                    var pros = eDataContext.Demands
                        .Where(e => demandTypeID > 0 ? e.DemandTypeID == demandTypeID : true)  // Inseted by Vietlv(AddDate:25/07/2011)
                        .Where(p => (catID > 0 ? p.CatID == catID : true))
                        .Where(p => currentPub.HasValue ? p.PubYN == (currentPub.HasValue && currentPub.Value == 1 ? true : false) : true)
                        .Where(p => (string.IsNullOrEmpty(keyword) ? true : p.Title.ToLower().Contains(keyword.ToLower().Trim())))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<DemandCategory> categories = eDataContext.DemandCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    var listDemandType = eDataContext.DemandTypes.ToList();  // Inseted by Vietlv(AddDate:25/07/2011)
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new DemandViewModels
                    {
                        Demand = pros,
                        Categories = categories,
                        CurrentCat = catID,
                        CurrentPubStatus = currentPub,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ProjectRootUrl,
                        DemandTypes = listDemandType, // Inseted by Vietlv(AddDate:25/07/2011)
                        CurrentDemandTypes = demandTypeID // Inseted by Vietlv(AddDate:25/07/2011)
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Demands/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                    //DemandCategory proCat = eDataContext.DemandCategories.Where(c => c.ID == id).SingleOrDefault();
                    //List<DemandCategory> categories = eDataContext.DemandCategories
                    //                                    .Where(c => c.ID != id)
                    //                                    .ToList();
                    Demand d = eDataContext.Demands.Where(de => de.ID == id).FirstOrDefault();
                    var currentDemandType = eDataContext.DemandTypes.Where(e => e.ID == d.DemandTypeID).SingleOrDefault();
                    return View(new DemandInputModels
                    {
                        ID = id,
                        Demand = d,
                        DemandType = currentDemandType
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Demands/Create
        public ActionResult Create()
        {
            try
            {
                    List<DemandCategory> categories = eDataContext.DemandCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    List<City> listC = eDataContext.Cities.ToList();
                    List<DemandType> listDemandType = eDataContext.DemandTypes.ToList();
                    var listCurrency = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(), ",");
                    var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(),",");
                    var listExpireDate = Utils.StringToDictionary(Settings.Default.ListDemandExpire.ToString(),",");
                    return View(new DemandInputModels
                    {
                        Categories = categories,
                        ListCity = listC,
                        DemandTypes = listDemandType,
                        ListCurrency = listCurrency,
                        ListUnitCost = listUnitCost,
                        ListExpireDate = listExpireDate
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Demands/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(DemandInputModels m)
        {
            try
            {
                    UpdateModel(m);
                    m.Demand.AddBy = UserManager.GetUserId();
                    m.Demand.AddDate = DateTime.Now;
                    var expireDate = Request["ExpireDateTime"] !=null ? Convert.ToInt32(Request["ExpireDateTime"]) : 0;
                    m.Demand.ExpireDate = DateTime.Now.AddDays(expireDate);
                    #region cost convert
                    // Case currency is "VND"
                    if (m.Demand.CurrencyID == 1)
                    {
                        //Case unit cost is VND/m2
                        if (m.Demand.UnitCostID == 1 && m.Demand.Area !=null)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                        }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                        // Case unit cost is VND/m2/tháng
                        if (m.Demand.UnitCostID == 2)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                           
                            m.Demand.TotalCost =Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        // Case unit cost is VND/tổng diện tích
                        if (m.Demand.UnitCostID == 3)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = m.Demand.Cost;
                        }
                        m.Demand.CurrencyName = "VND";
                    }
                    // Case currency is "USD"
                    if (m.Demand.CurrencyID == 2)
                    {
                        //Case unit cost is USD/m2
                        if (m.Demand.UnitCostID == 1)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = int.Parse(Settings.Default.USD) * Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost.Value;
                        }
                        // Case unit cost is USD/m2/tháng
                        if (m.Demand.UnitCostID == 2 )
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = int.Parse(Settings.Default.USD) * Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        //Case unit cost is USD/Tổng
                        if (m.Demand.UnitCostID == 3 )
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = int.Parse(Settings.Default.USD) * m.Demand.Cost.Value;
                        }
                        m.Demand.CurrencyName = "USD";
                    }
                    // Get DemandConvertPriceID     
                    if (m.Demand.Cost.HasValue)
                    {
                        m.Demand.DemandConvertPrice = GetConvertPriceID(m.Demand.Cost.Value, m.Demand.DemandTypeID.Value);
                    }

                    // Get DemandConvertAreaID
                    if (m.Demand.Area != null)
                    {
                        var area = Convert.ToDouble(m.Demand.Area);
                        m.Demand.DemandConvertArea = GetConvertAreaID(area, m.Demand.DemandTypeID.Value);
                    }
                    #endregion

                    eDataContext.Demands.InsertOnSubmit(m.Demand);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Demands/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    Demand d = eDataContext.Demands.Where(de => de.ID == id).FirstOrDefault();
                    List<DemandCategory> categories = eDataContext.DemandCategories
                                                    .Where(c => c.ActiveYN.HasValue && c.ActiveYN.Value == true)
                                                    .ToList();
                    List<City> listC = eDataContext.Cities.ToList();
                    List<District> listD = eDataContext.Districts.Where(di => di.CityID == d.CityID).ToList();
                    var listDemandType = eDataContext.DemandTypes.ToList();
                    int currentDemandType =Convert.ToInt32(d.DemandTypeID.HasValue);
                    var listCurrentcy = Utils.StringToDictionary(Settings.Default.ListCurrency.ToString(),",");
                    var listUnitCost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",");
                    var listExpiredDate = Utils.StringToDictionary(Settings.Default.ListDemandExpire.ToString(),",");
                    return View(new DemandInputModels
                    {
                        ID = id,
                        Demand = d,
                        Categories = categories,
                        ListCity = listC,
                        ListDistrict = listD,
                        DemandTypes = listDemandType,
                        CurrentDemandType = currentDemandType,
                        ListCurrency = listCurrentcy,
                        ListExpireDate = listExpiredDate,
                        ListUnitCost = listUnitCost
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Demands/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, DemandInputModels m)
        {
            try
            {
                
                    m.Demand = eDataContext.Demands.Where(d => d.ID == id).FirstOrDefault();
                    UpdateModel(m);
                    var exdate = Request["RangeExpireDate"] != null && Request["RangeExpireDate"] != string.Empty ? Convert.ToInt32(Request["RangeExpireDate"]) : 0;
                    if (exdate > 0) m.Demand.ExpireDate.Value.AddDays(exdate);
                    m.Demand.ModifyBy = UserManager.GetUserId();
                    m.Demand.ModifyDate = DateTime.Now;
                    var cost = Request["DemandCost"] != null && Request["DemandCost"] != string.Empty ? Convert.ToDecimal(Request["DemandCost"]) : 0;
                    var area = Request["DemandArea"] != null && Request["DemandArea"] != string.Empty ? Convert.ToDouble(Request["DemandArea"]) : 0;
                    // Get DemandConvertPriceID     
                    if (cost > 0)
                    {
                        m.Demand.DemandConvertPrice = GetConvertPriceID(cost, m.Demand.DemandTypeID.Value);
                    }
                    // Get DemandConvertAreaID
                    if (area != null)
                    {
                        m.Demand.DemandConvertArea = GetConvertAreaID(area, m.Demand.DemandTypeID.Value);
                    }
                    m.Demand.Cost = cost;
                    m.Demand.Area = area.ToString();
                   // UpdateModel(m);
                    #region cost convert
                    // Case currency is "VND"
                    if (m.Demand.CurrencyID == 1)
                    {
                        //Case unit cost is VND/m2
                        if (m.Demand.UnitCostID == 1 && m.Demand.Area != null)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                     // from  m.Product.UnitCost = costTypeID + new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2)  
                        }                                                                                             // To m.Product.UnitCost =new ProductUnitCode().GetDes(ProductUnitCode.Codes.M2);   
                        // Case unit cost is VND/m2/tháng
                        if (m.Demand.UnitCostID == 2)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }

                             m.Demand.TotalCost = Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        // Case unit cost is VND/tổng diện tích
                        if (m.Demand.UnitCostID == 3)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                             m.Demand.TotalCost = m.Demand.Cost;
                        }
                        m.Demand.CurrencyName = "VND";
                    }
                    // Case currency is "USD"
                    if (m.Demand.CurrencyID == 2)
                    {
                        //Case unit cost is USD/m2
                        if (m.Demand.UnitCostID == 1)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                             m.Demand.TotalCost = int.Parse(Settings.Default.USD) * Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost.Value;
                        }
                        // Case unit cost is USD/m2/tháng
                        if (m.Demand.UnitCostID == 2)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                             m.Demand.TotalCost = int.Parse(Settings.Default.USD) * Convert.ToDecimal(m.Demand.Area) * m.Demand.Cost;                                // Modifiedl by Vietlv from (Decimal)m.Product.Area.Value; to m.Product.Cost;
                        }
                        //Case unit cost is USD/Tổng
                        if (m.Demand.UnitCostID == 3)
                        {
                            var listUnistcost = Utils.StringToDictionary(Settings.Default.ListUnitCost.ToString(), ",").ToList();
                            foreach (var unitcost in listUnistcost)
                            {
                                var unitKey = Convert.ToInt32(unitcost.Key);
                                if (unitKey == m.Demand.UnitCostID) m.Demand.UnitCost = unitcost.Value.ToString();
                            }
                            m.Demand.TotalCost = int.Parse(Settings.Default.USD) * (decimal)m.Demand.Cost.Value;
                        }
                        m.Demand.CurrencyName = "USD";
                    }

                    eDataContext.SubmitChanges();
                    #endregion    
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Demands/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    Demand de = eDataContext.Demands.Where(d => d.ID == id).FirstOrDefault();
                    if (de == null)
                        throw new NullReferenceException();

                    return View(de);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Demands/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    Demand de = eDataContext.Demands.Where(d => d.ID == id).FirstOrDefault();
                    if (de != null)
                    {
                        var comments = eDataContext.Comments.Where(e => e.CommentInDemands.Where(k => k.DemandID == id).ToList().Count > 0).ToList();
                        eDataContext.CommentInDemands.DeleteAllOnSubmit(from e in eDataContext.CommentInDemands where e.DemandID == id select e);
                        eDataContext.Comments.DeleteAllOnSubmit(comments);
                        eDataContext.Demands.DeleteOnSubmit(de);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        #region / GetConvertPriceID
        private DemandConvertPrice GetConvertPriceID(decimal TotalPrice, int typeDemand)
        {
            try
            {
                if (TotalPrice < 0) throw new NotSupportedException();
                var maxValue = eDataContext.DemandConvertPrices.Max(e => e.MaxValue);
                if (TotalPrice > maxValue)
                {
                    var currentPriceID = eDataContext.DemandConvertPrices
                        .Where(e => e.TypeID == typeDemand)
                        .Where(e => e.MaxValue == maxValue).SingleOrDefault();
                    return currentPriceID;
                }
                var CurrentConvertPriceID = eDataContext.DemandConvertPrices
                                        .Where(ca => ca.TypeID == typeDemand)
                                        .Where(c => c.MinValue <= (decimal)TotalPrice && c.MaxValue >= (decimal)TotalPrice)  //// Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .SingleOrDefault();
                return CurrentConvertPriceID;

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region /GetConvertAreaID
        private DemandConvertArea GetConvertAreaID(double Area, int typeDemand)
        {
            try
            {
                if (Area < 0) throw new NotSupportedException();
                var maxArea = eDataContext.DemandConvertAreas
                    .Where(e => e.TypeID == typeDemand)
                    .OrderByDescending(e => e.MaxValue)
                    .FirstOrDefault();
                if (Area > Convert.ToDouble(maxArea.MaxValue))
                {
                    return maxArea;
                }
                var CurrentConvertAreaID = eDataContext.DemandConvertAreas
                                        .Where(ca => ca.TypeID == typeDemand)
                                        .Where(c => c.MinValue <= (decimal)Area && c.MaxValue >= (decimal)Area) // Modified by Vietlv test vaule of boundaris (">" --> ">=")
                                        .FirstOrDefault();
                return CurrentConvertAreaID;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
